package com.anlu.thread.ta3;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @description:
 * @author: Andrew
 * @create: 2019-01-30 15:26
 **/
public class Demo {

    private Map<String,Object> map=new HashMap<>();
    //读写互斥的锁
    private ReadWriteLock rw1=new ReentrantReadWriteLock();

    //读的锁
    private Lock r = rw1.readLock();
    //写的锁
    private Lock w = rw1.writeLock();

    public Object get(String key){
        r.lock();
        System.out.println(Thread.currentThread().getName()+"读操作进行");

        try{
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return map.get(key);
        }finally {
            r.unlock();
            System.out.println(Thread.currentThread().getName()+"读操作执行完毕");
        }
    }

    /**
     *
     * @param key
     * @param value
     */
    public void put(String key,Object value){
        w.lock();

        System.out.println(Thread.currentThread().getName() + " 写操作在执行..");
        try{
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            map.put(key, value);
        }finally {
            w.unlock();
            System.out.println(Thread.currentThread().getName() + " 写操作执行完毕..");

        }

    }

}
